// src/filters/unauthorized.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
import { UnauthorizedException } from '@nestjs/common';

@Catch(HttpException)
export class UnauthorizedFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();
        const status = exception.getStatus();

        if (exception instanceof UnauthorizedException) {
            // 自定义错误响应
            response.status(status).json({
                message: '验证身份信息失败',
                statusCode: status,
                timestamp: new Date().toISOString(),
                path: request.url,
            });
        } else {
            // 其他异常使用默认处理
            response.status(status).json({
                statusCode: status,
                message: exception.message,
                timestamp: new Date().toISOString(),
                path: request.url,
            });
        }
    }
}